/**
 * @description 非mini型uiless-member不和panel结合使用
 */

import React from 'react';
import PropTypes from 'prop-types';
import Member from '@alife/yunxiao-member';
import { ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import exceed from 'utils/apimap';
import { getFeature } from 'utils/features';
import { customMemberSearchAll } from 'api';

const { organization_id } = window.FORCE.organization;

export default class CodeMemberList extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    title: PropTypes.string,
    onChange: PropTypes.func,
    memberVisible: PropTypes.bool,
    closeModal: PropTypes.func,
    //  true 标识从mini点击出现弹窗，则是1人企业，不需要发请求。
    clickFromMiniMember: PropTypes.bool,
  };

  static defaultProps = {
    trigger: null,
    title: null,
    onChange: () => {},
    memberVisible: false,
    closeModal: () => {},
    clickFromMiniMember: false,
  };

  constructor(props) {
    super(props);
    this.state = {
      // 企业成员
      orgMembers: [],
      memberLoading: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      memberVisible: props.memberVisible,
    };
  }

  componentDidMount() {
    if (!this.props.trigger && !this.props.clickFromMiniMember) {
      this.showModal();
    }
  }

  showModal = () => {
    this.getOrgMembers(() => {
      this.setState({
        memberVisible: true,
      });
    });
  };

  onClose = () => {
    this.setState({
      memberVisible: false,
    });
    this.props.closeModal();
  };

  getOrgMembers = (cb) => {
    this.setState({
      memberLoading: true,
    });
    exceed
      .forceFetch({
        api: 'organization.member',
        params: {
          orgId: organization_id,
        },
      })
      .then((result) => {
        this.setState({
          orgMembers: result.result || [],
          memberLoading: false,
        });
        cb && cb();
      })
      .catch((err) => {
        this.setState({
          memberLoading: false,
        });
        cb && cb();
        console.log(err);
      });
  };

  onMemberClose = () => {
    this.setState({
      memberVisible: false,
    });
    if (this.state.orgMembers.length === 1) {
      this.getOrgMembers();
    }
    this.props.closeModal();
  };

  render() {
    const { title, onChange, trigger, addMembersDisabled, clickFromMiniMember, value, ...others } =
      this.props;
    const { orgMembers, memberVisible, memberLoading } = this.state;

    const orgRole = (window.FORCE.organization && window.FORCE.organization.user_role) || '';
    const isOrgAdmin = orgRole ? ORGANIZATION_ADMIN_ROLES.includes(orgRole) : false;
    // 临时方案，等底座后端邀请链接重构后即可去掉
    const nextUrl = encodeURIComponent(`${location.origin}?org_id=${organization_id}`);
    const inviteUrl = `https://devops.aliyun.com/org-admin/${organization_id}/members/member?invite=true&next_url=${nextUrl}`;

    return (
      <React.Fragment>
        <Member
          visible={memberVisible}
          value={value}
          title={title}
          multiple
          mode="add"
          autoFocus
          onChange={(users) => {
            this.setState({
              memberVisible: false,
            });
            onChange(users);
          }}
          isAdmin={isOrgAdmin}
          inviteUrl={inviteUrl}
          // 企业只有自己的时候传moreInvite  否则传'home'
          defaultPage={clickFromMiniMember || orgMembers.length === 1 ? 'moreInvite' : 'home'}
          onRequestClose={this.onMemberClose}
          onInviteBack={this.getOrgMembers}
          loading={memberLoading}
          // 部门本次先不接
          // extraMemberTypes={['team', 'more_invite']}
          extraMemberTypes={getFeature('member.memberWithInvite.extraMemberTypes')}
          customSearchAll={getFeature('member.customSearchAll') ? customMemberSearchAll : undefined}
          {...others}
        />
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
